package com.yange.accountbook.ui

import android.os.Bundle
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.interfaces.OnConfirmListener
import com.yange.accountbook.R
import com.yange.accountbook.databinding.DetailedManageFragmentLayoutBinding
import com.yange.accountbook.entity.IconEntity
import com.yange.accountbook.net.Api
import com.yange.accountbook.net.BaseResponse
import com.yange.accountbook.net.api.RetrofitClient
import com.yange.accountbook.net.observable.RecObserver
import com.yange.accountbook.utils.image.loadCircleImg
import com.yange.accountbook.utils.showToast
import com.yanzhenjie.recyclerview.touch.OnItemMoveListener
import java.util.*
import java.util.stream.Collectors

class DetailedManageFragment:BaseFragment<DetailedManageFragmentLayoutBinding>() {


    lateinit var iconAdapter:IconAdapter

    override fun initView() {
        iconAdapter = IconAdapter()

        initListener()

        binding.listData.layoutManager = LinearLayoutManager(activity)
        binding.listData.adapter = iconAdapter

        getIconList()
    }

    override fun initData() {

    }

    companion object {
        fun newInstance(type: String): DetailedManageFragment {
            var fragment = DetailedManageFragment()
            var bundle = Bundle()
            bundle.putString("type", type)
            fragment.arguments = bundle
            return fragment
        }
    }

    fun initListener() {
        binding.tvAdd.setOnClickListener {
            //新增条目
            activity?.let { it1 ->
                arguments?.getString("type")
                    ?.let { it2 -> AddDetailedTypeActivity.start(it1, it2) }
            }
        }

        binding.listData.isLongPressDragEnabled = true
        binding.listData.setOnItemMoveListener(object : OnItemMoveListener {
            override fun onItemMove(
                srcHolder: RecyclerView.ViewHolder?,
                targetHolder: RecyclerView.ViewHolder?
            ): Boolean {
                // 此方法在Item拖拽交换位置时被调用。
                // 第一个参数是要交换为之的Item，第二个是目标位置的Item。
                // 交换数据，并更新adapter。
                val fromPosition = srcHolder!!.adapterPosition
                val toPosition = targetHolder!!.adapterPosition
                Collections.swap(iconAdapter.data, fromPosition, toPosition)
                iconAdapter.notifyItemMoved(fromPosition, toPosition)
                //这里先改本地数据，然后再悄悄该后台数据，不然操作不流畅
                changeSort()
                // 返回true，表示数据交换成功，ItemView可以交换位置。
                return true
            }

            override fun onItemDismiss(srcHolder: RecyclerView.ViewHolder?) {


            }
        })

    }

    fun changeSort() {
        RetrofitClient.getInstance().feeItemSort(
            context, Api.FEE_ITEM_SORT,
            iconAdapter.data.stream().map { it.id }.collect(Collectors.toList())
        ).subscribe(object : RecObserver<BaseResponse<Any>>(context, false, false) {
            override fun onSuccess(t: BaseResponse<Any>?) {}
            override fun onFail(msg: String, code: Int) {}
        })
    }

    private fun getIconList() {
        RetrofitClient.getInstance().invokeGetIconList(activity, arguments?.getString("type"))
            .subscribe(object :
                RecObserver<BaseResponse<List<IconEntity>>>(activity, false, false) {
                override fun onSuccess(t: BaseResponse<List<IconEntity>>?) {
                    if (!t?.data.isNullOrEmpty()) {
                        iconAdapter.setNewInstance(t?.data as MutableList<IconEntity>?)
                    }
                }

                override fun onFail(msg: String, code: Int) {

                }
            })
    }


    class IconAdapter :
        BaseQuickAdapter<IconEntity, BaseViewHolder>(R.layout.item_detailed_manage_layout) {
        override fun convert(holder: BaseViewHolder, item: IconEntity) {
            var image = holder.getView<ImageView>(R.id.iv_icon)
            context.loadCircleImg(image, item.icon)
            holder.setText(R.id.tv_title, item.name)
            if ("USER" == item.type) {
                holder.setVisible(R.id.iv_delete, true)
                holder.setVisible(R.id.tv_type, true)
            }
            holder.getView<ImageView>(R.id.iv_delete).setOnClickListener {
                XPopup.Builder(context)
                    .asConfirm("提示", "确认删除该费用项吗？", OnConfirmListener {
                        deleteItem(item.id, holder.layoutPosition)
                    }).show()
            }
        }

        fun deleteItem(id:Int,position: Int){
            var arrayList = ArrayList<Int>()
            arrayList.add(id)
            RetrofitClient.getInstance().deleteRecord(context,Api.FEEITEM_DELETE,arrayList)
                .subscribe(object :RecObserver<BaseResponse<Any>>(context,true,false){
                    override fun onSuccess(t: BaseResponse<Any>?) {
                        removeAt(position)
                        notifyItemRemoved(position)
                    }
                    override fun onFail(msg: String, code: Int) {
                       showToast(msg)
                    }

                })
        }
    }

    override fun onResume() {
        super.onResume()
        getIconList()
    }
}